package com.atguigu.day06;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.triggers.TriggerResult;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Example5 {
    public static void main(String[] args) {
        var env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                // "a 1234"
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String in) throws Exception {
                        var arr = in.split(" ");
                        return Tuple2.of(
                                arr[0],
                                Long.parseLong(arr[1])
                        );
                    }
                })
                // 在map输出的数据流中插入水位线事件
                // `.assignTimestampsAndWatermarks`默认每隔200毫秒向下游发送一条水位线数据
                .assignTimestampsAndWatermarks(
                        // `Duration.ofSeconds(5)`表示设置 `最大延迟时间` 为5秒钟
                        WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner((element, recordTimestamp) -> element.f1)
                )
                .keyBy(r -> r.f0)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .trigger(new Trigger<>() {
                    @Override
                    public TriggerResult onElement(Tuple2<String, Long> in, long ts, TimeWindow w, TriggerContext ctx) throws Exception {
                        var flag = ctx.getPartitionedState(
                                new ValueStateDescriptor<>(
                                        "flag",
                                        Types.BOOLEAN
                                )
                        );

                        if (flag.value() == null) {
                            flag.update(true);

                            ctx.registerEventTimeTimer(in.f1 + 1000L - in.f1 % 1000L);
                        }

                        return TriggerResult.CONTINUE;
                    }

                    @Override
                    public TriggerResult onProcessingTime(long l, TimeWindow timeWindow, TriggerContext triggerContext) throws Exception {
                        return null;
                    }

                    @Override
                    public TriggerResult onEventTime(long timerTs, TimeWindow timeWindow, TriggerContext triggerContext) throws Exception {
                        System.out.println("timerTs: " + timerTs);
                        if (timerTs < timeWindow.getEnd() - 1L) {
                            if (timerTs + 1000L < timeWindow.getEnd() - 1L) {
                                triggerContext.registerEventTimeTimer(timerTs + 1000L);
                            }
                            return TriggerResult.FIRE;
                        }
                        return TriggerResult.FIRE_AND_PURGE;
                    }

                    @Override
                    public void clear(TimeWindow timeWindow, TriggerContext ctx) throws Exception {
                        var flag = ctx.getPartitionedState(
                                new ValueStateDescriptor<>(
                                        "flag",
                                        Types.BOOLEAN
                                )
                        );

                        flag.clear();
                    }
                })
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String key, Context context, Iterable<Tuple2<String, Long>> elements, Collector<String> collector) throws Exception {
                        // 获取迭代器中的元素数量
                        var count = elements.spliterator().getExactSizeIfKnown();

                        collector.collect("key：" + key + ", 窗口：" + context.window().getStart() + "~" +
                                "" + context.window().getEnd() + ",元素数量：" + count);
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
